﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Slja.BLL;
using Slja.Model;
using Slja.Utility;
using Slja.Model.Platform;
using Slja.BLL.Platform;
using System.Web.UI.HtmlControls;

namespace FrameWork.web.Web.Project.SelPage
{
    public partial class MailBuilder : System.Web.UI.Page
    {
        public int OrderID
        {
            get { return int.Parse(Request.QueryString["orderid"]); }
        }
        OrderExtModel _Order;
        public OrderExtModel Order
        {
            get {
                if (_Order == null)
                {
                    if (ViewState["_Order"] == null)
                    {
                        OrderBLL bll = new OrderBLL();
                        _Order = bll.GetModelExt(OrderID, true);
                        ViewState["_Order"] = _Order;                       
                    }
                    else
                    {
                        _Order = (OrderExtModel)ViewState["_Order"];                      
                    }
                }
                return _Order;               
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            btnSend.Click += new EventHandler(btnSend_Click);
            dliAttaches.ItemDataBound += new DataListItemEventHandler(dliAttaches_ItemDataBound);
            if (!IsPostBack)
            {
                //OrderBLL bll = new OrderBLL();
                //OrderExtModel Order = bll.GetModelExt(OrderID, true);
                //收件人地址
                #region 收件人
                if (Order.PlanMaker.HasValue && Order.PlanMaker.Value ==0 )
                {
                    LinkManModel planmaker = new LinkManBLL().GetModel(Order.PlanMaker.Value);
                    if (planmaker != null &&!string.IsNullOrEmpty(planmaker.Email)) { tlbRecivers.Text += planmaker.Email + ";"; }
                }
                if (Order.SaleMan.HasValue && Order.SaleMan.Value != 0)
                {
                    LinkManModel SaleMan = new LinkManBLL().GetModel(Order.SaleMan.Value);
                    if (SaleMan != null && !string.IsNullOrEmpty(SaleMan.Email)) { tlbRecivers.Text += SaleMan.Email + ";"; }  
                }
                if (Order.AgentClientID.HasValue && Order.AgentClientID.Value != 0)
                {
                    LinkManModel AgentClient = new LinkManBLL().GetModel(Order.AgentClientID.Value);
                    if (AgentClient != null &&!string.IsNullOrEmpty(AgentClient.Email)) { tlbRecivers.Text += AgentClient.Email + ";"; }
                }


                if (Order.Creator.HasValue && Order.Creator!=0)
                {
                    UserModel Creater = new UserBLL().GetModel(Order.Creator.Value);
                    tlbCC.Text += Creater.U_Email + ";";
                }
                #endregion
                //抄送人
                #region 抄送人
                OrderWorkTeamModel Design = Order.WorkTeam.Find(delegate(OrderWorkTeamModel m) { return m.enum_WorkRole == Slja.Utility.WorkerRole.OrderDesigner; });
                if (Design != null)
                {
                    UserModel DesignUser = new UserBLL().GetModel(Design.WorkerID);
                    tlbCC.Text += DesignUser.U_Email + ";";
                }
                #endregion

                
                //附件类型
                string AttType = "";
                //附件
                if (Order.Enum_SaleState == SaleState.DesignUp)
                {

                    dliAttaches.DataSource = Order.FileList.FindAll(
                        delegate(OrderFilesModel f)
                        {
                            return f.enum_FileClass == Slja.Utility.FileClass.DrawingContruction
                                || f.enum_FileClass == Slja.Utility.FileClass.DrawingScene
                                || f.enum_FileClass == Slja.Utility.FileClass.DrawingPlane;
                        });
                    dliAttaches.DataBind();
                    AttType = "图纸";
                   
                }
                else if (Order.Enum_SaleState == SaleState.PriceUp)
                {
                    dliAttaches.DataSource = Order.FileList.FindAll(
                        delegate(OrderFilesModel f)
                        {
                            return f.enum_FileClass == Slja.Utility.FileClass.FileQuotation;
                               
                        });
                    dliAttaches.DataBind();
                    AttType = "报价";
                }
                //标题
                tlbTitle.Text = string.Format("请确认{2}([{0}]{1}）", Order.PrjID, Order.PrjName, AttType);
                //正文
                tlbContent.Text = @"    您好！
请确认" + AttType + @". 谢谢！   
     --"+Order.ManagerUserName + DateTime.Today.ToString("yyyy-MM-dd");
                
            }

        }

        void dliAttaches_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item ||
                e.Item.ItemType == ListItemType.AlternatingItem)
            {
                OrderFilesModel model = e.Item.DataItem as OrderFilesModel;

                HtmlInputCheckBox chx = e.Item.FindControl("chxAtt") as HtmlInputCheckBox;
                if (chx != null)
                {
                    chx.Checked = true;
                    chx.Value = model.ID.ToString();

                }
                HtmlGenericControl lb = e.Item.FindControl("lbatt") as HtmlGenericControl;
                lb.InnerHtml = string.Format("({0})<a href='#'>{1}</a>", model.enum_FileClass.ToDescription(),model.FileName);

            }
        }
        void btnSend_Click(object sender, EventArgs e)
        {
            string[] recivers = tlbRecivers.Text.Trim().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[] CC = tlbCC.Text.Trim().Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries);
            string attids = "0";
            for(int i=0;i<dliAttaches.Items.Count;i++)
            {
                 HtmlInputCheckBox chx = dliAttaches.Items[i].FindControl("chxAtt") as HtmlInputCheckBox;
                if (chx != null)
                {
                    if(chx.Checked)
                    {
                        attids += ","+chx.Value;
                    }
                }
            }
            List<OrderFilesModel> filebll = new OrderFilesBLL().GetModelList(" ID in("+attids+")");
            WebCommon.SendMail(recivers, CC, tlbTitle.Text.Trim(), tlbContent.Text.Trim(), filebll);
            //提交或保存日志
            SubmitOrderOrLog();           
            ScriptManager.RegisterStartupScript(Page, typeof(Page), "Mailbuild", "window.returnValue=true;alert('邮件发送成功');window.setTimeout(function(){window.close();}, 1000);", true);
           // WebCommon.AlertMsg(Page, "邮件发送成功！");
            
        }
        void SubmitOrderOrLog()
        {
            
            OrderBLL orderBLL = new OrderBLL();
            OrderSubmitModel submit = new OrderSubmitModel();
            OrderLogModel log = new OrderLogModel();
            if (Order.Enum_SaleState == SaleState.DesignUp
                || Order.Enum_SaleState == SaleState.PriceUp)
            {
                submit.BackState = null;
                submit.OrderID = Order.ID;
                submit.SubmitSaleStateLog = Order.SaleStateLog | (int)Order.Enum_SaleState * 2;
               
                submit.NextOpUserID = Order.ManagerUser;
                submit.NextOpUserName = Order.ManagerUserName;
                {
                    log.CurState = (int)Order.Enum_SaleState;
                    log.Dtm = DateTime.Now;
                    log.NextState = (int)Order.Enum_SaleState * 2;
                    log.NextUser = Order.ManagerUser;
                    log.Note = "提交,并发送邮件";
                    log.OpType = (int)(Btn.Submit|Btn.SendMail);
                    log.OrderID = Order.ID;
                    log.UserID = Common.Get_UserID;
                    log.UserName = UserData.GetUserData.U_CName;
                }
                //提交，带日志
                orderBLL.SubmitWithLog(submit, log);
            }
            else
            {             
                {
                    log.CurState = (int)Order.Enum_SaleState;
                    log.Dtm = DateTime.Now;
                    log.NextState = log.CurState;
                    log.NextUser = Order.ManagerUser;
                    log.Note = "发送邮件";
                    log.OpType = (int)Btn.SendMail;
                    log.OrderID = Order.ID;
                    log.UserID = Common.Get_UserID;
                    log.UserName = UserData.GetUserData.U_CName;
                }
                //仅仅保存日志 （邮件发送不成功，允许再次发送，但记录日志）              
                new OrderLogBLL().Add(log);
            }

           
            
           
            orderBLL.SubmitWithLog(submit, log);
        }
    }
}